<template>
  <div class="identityInfo">
    <van-nav-bar
        left-arrow
        @click-left="handleClickLeft"
        :title="$t('身份认证')"
    >
    </van-nav-bar>
    <div class="tab_progress">
      <span style="vertical-align: middle;background-color: #FFE1AD;padding: 10px;border-radius: 20px">Step 5</span>
    </div>
    <div style="margin-top: 20px;background-color: #FFFFFF;padding: 15px 0">
      <!--     身份信息-->
      <div class="cell_content_list">
        <!--      选择身份证类型-->
        <div class="cell_content_item" @click="idCardTypeShow = true" v-if="resourcesShow['gender'] === 1">
          <div class="text">
            {{ $t('身份证类型') }}
          </div>
          <div style="position: relative">
            <input class="input" @blur="confirmPoint(1)" v-model="userInfo.typeOfCertificate" :readonly="true"
                   :placeholder="$t('身份证类型')"/>
            <img class="input_icon" src="../../assets/my/input_right.png">
          </div>
          <div style="margin-top: 10px;font-size: 12px;color: #9F9DAB">
            <p>1. Please ensure that the ID photo uploaded matches the ID type selected above</p>
            <div>2. Please ensure that the uploaded photo is <span
                style="color: #FF7805">clear, neat and unobstructed,</span>
              otherwise it will affect the recognition
            </div>
          </div>
        </div>
        <div style="display: flex;justify-content: space-around;align-items: center;margin-top: 10px">
          <!--        上传身份证正面-->
          <div class="cell_content_item" v-if="resourcesShow['frontIdCardUrl'] === 1">
            <div class="card_box">
              <div style="text-align: center">
                <van-uploader accept=".jpg,.jpeg,.png,.JPG,.JPEG" capture="camera"
                              :before-read="beforeRead"
                              :after-read="updatePositive">
                  <img class="idCard_img" v-if="userInfo.positive" :src="userInfo.positive">
                  <img class="idCard_img" v-else src="../../assets/identity/card_img_front.png">
                </van-uploader>
              </div>
              <div class="title">
                <div>Front photo of ID card</div>
                <div class="title_tips">Upload a front-facing photo of your ID</div>
              </div>
            </div>
          </div>
          <!--        上传身份证反面-->
          <div class="cell_content_item" v-if="resourcesShow['negativeIdCardUrl'] === 1 " >
            <div class="card_box">

              <div style="text-align: center">
                <van-uploader accept=".jpg,.jpeg,.png,.JPG,.JPEG" capture="camera"
                              :before-read="beforeRead"
                              :after-read="updateReverseSide">
                  <img class="idCard_img" v-if="userInfo.reverseSide" :src="userInfo.reverseSide">
                  <img class="idCard_img" v-else src="../../assets/identity/card_img_back.png">
                </van-uploader>
              </div>
              <div class="title">
                <div>Back side photo of ID</div>
                <div class="title_tips">Upload the back of your ID</div>
              </div>
            </div>
          </div>
        </div>
        <!--        上传身份证手持-->
        <div class="cell_content_item" v-if="resourcesShow['handIdCardUrl'] === 1" style="margin-top: 20px">
          <div class="card_box">
            <div style="text-align: center">
              <van-uploader accept=".jpg,.jpeg,.png,.JPG,.JPEG" capture="camera"
                            :before-read="beforeRead"
                            :after-read="updateHold">
                <img class="idCard_img" v-if="userInfo.hold" :src="userInfo.hold">
                <img class="idCard_img" v-else src="../../assets/identity/card_img_face.png">
              </van-uploader>
            </div>
            <div class="title">
              <div>Holding ID photo</div>
              <div class="title_tips">Please take a photo holding your ID</div>
            </div>
          </div>
        </div>
        <!--      身份证号码-->
        <div class="cell_content_item" v-if="resourcesShow['idcard'] === 1">
          <div class="text">
            {{ $t('身份证号码') }}
          </div>
          <input class="input" :readonly="isOcrIdentify"
                 @blur="confirmPoint(3)"
                 v-model="userInfo.idCard"
                 :placeholder="$t('请输入')"/>
        </div>
        <!--        父姓-->
        <div class="cell_content_item " style="display: block" v-if="resourcesShow['name'] === 1">
          <div class="text">
            First name
          </div>
          <input class="input" @blur="confirmPoint(4)" v-model="userInfo.fatherSurname" :readonly="isOcrIdentify"
                 :placeholder="$t('请输入')"/>
        </div>
        <!--        母姓-->
        <div class="cell_content_item " style="display: block" v-if="resourcesShow['name'] === 1">
          <div class="text">
            Middlet name
          </div>
          <input class="input" @blur="confirmPoint(5)" v-model="userInfo.motherSurname" :readonly="isOcrIdentify"
                 :placeholder="$t('请输入')"/>
        </div>
        <!--        姓名-->
        <div class="cell_content_item " style="display: block" v-if="resourcesShow['name'] === 1">
          <div class="text">
            last name
          </div>
          <input class="input" @blur="confirmPoint(6)" v-model="userInfo.secondName" :readonly="isOcrIdentify"
                 :placeholder="$t('请输入')"/>
        </div>
        <!--      选择性别-->
        <div class="cell_content_item" @click="selectSex" v-if="resourcesShow['gender'] === 1">
          <div class="text">
            {{ $t('性别') }}
          </div>
          <div style="position: relative">
            <input class="input" @blur="confirmPoint(7)" v-model="userInfo.gender" :readonly="true"
                   :placeholder="$t('请选择')"/>
            <img class="input_icon" src="../../assets/my/input_right.png">
          </div>
        </div>
        <!--      选择生日-->
        <div class="cell_content_item" @click="selectBirth" v-if="resourcesShow['dateBirth'] === 1">
          <div class="text">
            {{ $t('生日') }}
          </div>
          <div style="position: relative">
            <input class="input" @blur="confirmPoint(8)" v-model="userInfo.dateBirth" :readonly="true"
                   :placeholder="$t('请选择')"/>
            <img class="input_icon" src="../../assets/my/input_right.png">
          </div>
        </div>

      </div>
      <!--       选择性别-->
      <van-action-sheet v-model:show="sexShow" :actions="sexActions" @select="onSexSelect"/>
      <!--        证件下拉选择-->
      <van-action-sheet v-model:show="idCardTypeShow">
        <van-picker @confirm="idCardTypeConfirm" @cancel="idCardTypeShow = false"
                    :columns-field-names="{  text: 'value'}"
                    :columns="idCardTypeColumns"/>
      </van-action-sheet>
      <!--      选择生日-->
      <van-action-sheet v-model:show="birthdayShow">
        <van-datetime-picker
            @confirm="onBirthdaySelect"
            @cancel="birthdayShow = false"
            v-model="currentDate"
            :columns-order="['day', 'month', 'year']"
            type="date"
            :min-date="minDate"
            :max-date="maxDate"
        />
      </van-action-sheet>

      <van-popup v-model:show="dialogRetentionShow">
        <template #default>
          <div class="dialog_body">
            <div class="content_text">Application is successful immediately
              <p class="active">Get your money instantly in just 2 steps</p>
              Do you really want to quit?
            </div>
            <div style="margin-top: 20px;text-align: center">
              <van-button type="primary" style="width: 80%" @click="dialogRetentionShow = false" round>{{
                  $t('继续申请')
                }}
              </van-button>
              <van-button class="reject_btn" @click="$router.replace('/hScmlvxSUkDQ/UjRzDSClllpS')" round>
                {{ $t('残忍拒绝') }}
              </van-button>
            </div>
          </div>
        </template>
      </van-popup>
      <div style="text-align: center;margin: 25px 0; ">
        <van-button class="confirm" type="primary" round @click="confirm">{{ $t('继续') }}</van-button>
      </div>
    </div>
  </div>
</template>

<script>
import {ref, toRefs, reactive, onMounted,} from 'vue'
import {useRoute, useRouter} from 'vue-router'
import {useI18n} from 'vue-i18n'
import {dateFormat, debounce, processNext, setResourcesShow, compressImage, upLoadAdjustPoint} from '@/utils/tool'
import {Dialog, Toast} from 'vant'
import {
  uploadUserInfo,
  userInfoConfirm,
  personalInfoSelect,
  getAdvanceToken,
  getConfigSwitch,
  uploadOcr
} from '@/api/home'
import {fetchUserInfo, upLoadInputPoint, upLoadPoint} from '@/api/my'
import {useStore} from "vuex";

export default {
  components: {
    [Dialog.Component.name]: Dialog.Component,
  },
  setup() {
    const {t} = useI18n()
    const store = useStore()
    const isOcrIdentify = ref(false)
    const productName = localStorage.getItem('productName')
    const dialogRetentionShow = ref(false)
    const currentDate = ref(new Date(1990, 0, 1))
    let userInfo = reactive({
      name: null,
      idCard: null,
      gender: null,
      dateBirth: null,
      positive: null,
      reverseSide: null,
      hold: null,
      fatherSurname: null,
      motherSurname: null,
      secondName: null,
      typeOfCertificate: null,
    })
    const switchConfig = reactive({
      isLivingSwitch: false,
      isOcrSwitch: false,
      isFaceSwitch: false,
    })
    const resourcesShow = ref({})
    const routes = useRoute()
    const router = useRouter()
    const idCardTypeColumns = ref([])
    const idCardTypeShow = ref(false)
    let sexSheet = reactive({
      sexShow: false,
      sexActions: [{name: t('男'), key: 1}, {name: t('女'), key: 0}],
      onSexSelect: (value) => {
        userInfo.gender = value.name
        sexSheet.sexShow = false
      },
      selectSex: () => {
        if (isOcrIdentify.value) return
        sexSheet.sexShow = true
      }
    })
    // 选择生日
    let birthdaySheet = reactive({
      minDate: new Date(1910, 0, 1),
      maxDate: new Date(),
      endMaxDate: new Date(2090, 0, 1),
      birthdayShow: false,
      onBirthdaySelect: (value) => {
        userInfo.dateBirth = dateFormat(value, 'YYYY/mm/dd')
        birthdaySheet.birthdayShow = false
      },
      selectBirth: () => {
        if (isOcrIdentify.value) return
        birthdaySheet.birthdayShow = true
      }
    })
    const beforeRead = (file) => {
      if (!userInfo.typeOfCertificate) {
        Toast(t('请选择证件类型'))
        return Promise.reject()
      }
      return new Promise(async (resolve, reject) => {
        console.log(file)
        const fileType = ['image/jpeg', 'image/png', 'image/jpg']
        if (fileType.indexOf(file.type) === -1) {
          Toast('upload_image');
          reject()
        } else if (file.size < Math.pow((1024 * 1.35), 2)) {
          // 小于2m不压缩
          resolve(file)
        } else {
          // 压缩图片
          const caseFile = await compressImage(file)
          resolve(caseFile)
        }
      })
    }
    const upDateLoad = async (file, type) => {
      const formData = new FormData()
      formData.append('file', file)
      formData.append('type', type)
      const res = await uploadUserInfo(formData)
      if (res.code === 1 && res.data) {
        console.log(res.data)
        return res.data
      }
    }
    // 上传正面
    const updatePositive = async (file) => {
      Toast.loading({
        message: t('加载中'),
        forbidClick: true,
        duration: 0,
      })
      confirmPoint(2)
      // 上传接口
      const upload = async () => {
        const res = await upDateLoad(file.file, 2)
        userInfo.positive = res
      }
      // ocr 关闭
      if (!switchConfig.isOcrSwitch) {
        await upload()
        Toast.clear()
      } else {
        //该证件是否可以ocr识别
        const formData = new FormData()
        formData.append('file', file.file)
        formData.append('key', idCardTypeColumns.value.find(v => userInfo.typeOfCertificate === v.value).key)
        const res = await uploadOcr(formData)
        if (res.code === 1) {
          const data = JSON.parse(res.data)
          const formatData = matchCardTypeInfo(data.result, data.cardType)
          console.log(formatData)
          userInfo.idCard = formatData.idCard || null
          userInfo.gender = formatData.gender === 'M' ? t('男') : formatData.gender === 'F' ? t('女') : null
          userInfo.dateBirth = formatData.dateBirth ? formatData.dateBirth : null
          userInfo.fatherSurname = formatData.fatherSurname || null
          userInfo.motherSurname = formatData.motherSurname || null
          userInfo.secondName = formatData.secondName || null
          await upload()
          Toast.clear()
        } else {
          upLoadPoint({type: 4})
        }
      }
    }

    // 匹配ocr识别的结果
    function matchCardTypeInfo(data, cardType) {
      let dataObj = {
        idCard: null,
        gender: null,
        dateBirth: null,
        fatherSurname: null,
        motherSurname: null,
        secondName: null,
      }
      switch (cardType) {
        case 'UMID' :
          dataObj.idCard = data.idNumber
          dataObj.gender = data.gender
          dataObj.dateBirth = data.birthdayParsed
          dataObj.fatherSurname = data.givenName
          dataObj.motherSurname = data.middleName
          dataObj.secondName = data.surName
          break;
        case 'SSS' :
          dataObj.idCard = data.idNumber
          dataObj.dateBirth = data.birthdayParsed
          break;
        case 'TIN' :
          dataObj.idCard = data.idNumber
          dataObj.dateBirth = data.birthdayParsed
          break;
        case 'PASSPORT' :
          dataObj.idCard = data.idNumber
          dataObj.gender = data.gender
          dataObj.dateBirth = data.birthdayParsed
          dataObj.fatherSurname = data.givenName
          dataObj.motherSurname = data.middleName
          dataObj.secondName = data.surName
          break;
        case 'DRIVINGLICENSE' :
          dataObj.idCard = data.idNumber
          dataObj.gender = data.gender
          dataObj.dateBirth = data.birthdayParsed
          break;
        case 'NATIONALID' :
          dataObj.idCard = data.idNumber
          dataObj.dateBirth = data.birthdayParsed
          dataObj.fatherSurname = data.firstName
          dataObj.motherSurname = data.middleName
          dataObj.secondName = data.lastName
          break;
        case 'POSTALID' :
          dataObj.idCard = data.idNumber
          dataObj.dateBirth = data.birthdayParsed
          break;
        case 'VOTERID' :
          dataObj.idCard = data.idNumber
          dataObj.dateBirth = data.birthdayParsed
          break;
        case 'HEALTHCARD' :
          dataObj.idCard = data.idNumber
          dataObj.dateBirth = data.birthdayParsed
          dataObj.gender = data.gender
          break;
      }
      return dataObj
    }

    // 上传反面
    const updateReverseSide = async (file) => {
      Toast.loading({
        message: t('上传中'),
        forbidClick: true,
        duration: 0
      })
      confirmPoint(9)
      const res = await upDateLoad(file.file, 3)
      userInfo.reverseSide = res
      Toast.clear()
    }
    //上传手持
    const updateHold = async (file) => {
      Toast.loading({
        message: t('上传中'),
        duration: 0,
        forbidClick: true,
      })
      confirmPoint(10)
      const res = await upDateLoad(file.file, 1)
      userInfo.hold = res
      Toast.clear()
    }

    //获取所有下拉
    const getSelect = async () => {
      const res = await personalInfoSelect()
      idCardTypeColumns.value = res.data.filter(item => item.type === 26)
    }
    // 选择身份证
    const idCardTypeConfirm = ({value}) => {
      idCardTypeShow.value = false
      userInfo.typeOfCertificate = value
    }
    const handleLivingBody = () => {
      if (window.android) {
        window.android.startLivenessDetection()
      }
    }
    const verificationInfo = () => {
      let message = null
      const {
        idCard,
        gender,
        dateBirth,
        reverseSide,
        positive,
        hold, fatherSurname, motherSurname, secondName
      } = userInfo
      if (!positive && resourcesShow.value['frontIdCardUrl'] === 1) return message = t('请上传身份证正面')
      if (!reverseSide && resourcesShow.value['negativeIdCardUrl'] === 1) return message = t('请上传身份证反面')
      if (!hold && resourcesShow.value['handIdCardUrl'] === 1) return message = t('请上传手持身份证')
      if (!idCard && resourcesShow.value['idcard'] === 1) return message = t('身份证号码为空')
      // if (!checkIdcard()) return message = t('请输入正确的证件号码')
      if (!(fatherSurname && motherSurname && secondName) && resourcesShow.value['name'] === 1) return message = t('姓名为空')
      if (!gender && resourcesShow.value['gender'] === 1) return message = t('请选择性别')
      if (!dateBirth && resourcesShow.value['dateBirth'] === 1) return message = t('请选择生日')
      return message
    }
    const confirm = debounce(async () => {
      const message = verificationInfo()
      if (!message) {
        if (switchConfig.isLivingSwitch) {
          // 调用安卓活体检测页面
          if (window.android) {
            const isLiving = window.android.getLivenessImageUrl()
            console.log(isLiving)
            if (isLiving) {
              upLoadAdjustPoint({eventName:'xoi7o4'})
              next()
            } else {
              window.android.startLivenessDetection();
            }
          } else {
            next()
          }
        } else {
          next()
        }
      } else {
        upLoadPoint({type: 11})
        Toast({
          message: message
        })
      }
    }, 1000)
    // 下一步
    const next = async () => {
      const {fatherSurname, motherSurname, secondName, typeOfCertificate} = userInfo
      const params = {
        name: (fatherSurname + '-' + motherSurname + '-' + secondName).trim(),
        fatherSurname, motherSurname, secondName,
        idcard: userInfo.idCard,
        gender: userInfo.gender === t('男') ? 1 : 0,
        dateBirth: userInfo.dateBirth,
        typeOfCertificate: idCardTypeColumns.value.find(v => typeOfCertificate === v.value).key,
      }
      const res = await userInfoConfirm(params)
      if (res.code === 1) {
        Toast({
          message: t('提交成功')
        })
        const userWriteInfo = JSON.parse(sessionStorage.getItem('userWriteInfo'))
        localStorage.setItem('userWriteInfo', JSON.stringify({...userWriteInfo, name: userInfo.name}))
        processNext('identityInfo')
        upLoadAdjustPoint({eventName:'behj0y'})
      }
    }
    // 流程显示隐藏
    const getResourcesShow = async () => {
      resourcesShow.value = await setResourcesShow(1)
      // 清除loading
      store.dispatch('changeLoading', false)
    }


    // 获取用户信息回显
    async function getUserInfo() {
      fetchUserInfo().then(r => {
        if (r.code === 1) {
          const userWriteInfo = r.data
          userInfo.idCard = userWriteInfo.idcard
          userInfo.positive = userWriteInfo.frontIdCardUrl ? userWriteInfo.frontIdCardUrl : null
          userInfo.reverseSide = userWriteInfo.negativeIdCardUrl ? userWriteInfo.negativeIdCardUrl : null
          userInfo.hold = userWriteInfo.handIdCardUrl ? userWriteInfo.handIdCardUrl : null
          userInfo.gender = userWriteInfo.gender === '1' ? t('男') : userWriteInfo.gender === '0' ? t('女') : null
          userInfo.dateBirth = userWriteInfo.dateBirth
          userInfo.fatherSurname = userWriteInfo.fatherSurname
          userInfo.motherSurname = userWriteInfo.motherSurname
          userInfo.secondName = userWriteInfo.secondName
          userInfo.typeOfCertificate = idCardTypeColumns.value.find(v => userWriteInfo.typeOfCertificate === v.value).value || null
        }
      })
    }

    async function getSwitch() {
      const res = await getConfigSwitch({productName: productName})
      if (res.code === 1) {
        const {ocrSwitch, livingSwitch, faceSwitch} = res.data
        switchConfig.isLivingSwitch = livingSwitch === 1
        switchConfig.isOcrSwitch = ocrSwitch === 1
        switchConfig.isFaceSwitch = faceSwitch === 1
      }
    }

    // 提交埋点数据
    function confirmPoint(detailType) {
      upLoadInputPoint({
        type: 5,
        detailType: detailType
      })
    }

    function handleClickLeft() {
      upLoadPoint({type: 10})
      dialogRetentionShow.value = true
    }

    onMounted(() => {
      getResourcesShow()
      getSelect()
      getUserInfo()
      getSwitch()
    })
    return {
      dialogRetentionShow,
      handleLivingBody,
      isOcrIdentify,
      userInfo,
      handleClickLeft,
      confirmPoint,
      ...toRefs(sexSheet),
      ...toRefs(birthdaySheet),
      resourcesShow,
      currentDate,
      idCardTypeShow,
      idCardTypeColumns,
      beforeRead,
      updateReverseSide,
      updatePositive,
      updateHold,
      idCardTypeConfirm,
      confirm,
      next,
    }
  },
}
</script>

<style scoped lang="less">
.identityInfo {
  overflow: auto;

  .card_box {
    background-color: #ffffff;
    border-radius: 6px;
    .title {
      font-size: 15px;
      text-align: center;
      font-weight: 600;
      margin-right: 15px;
      padding: 10px 0;

      .title_tips {
        font-size: 10px;
        font-weight: 500;
        margin-top: 8px;
      }
    }

    .idCard_img {
      height: 80px;
      width: 120px;
    }
  }

  .tips {
    font-size: 14px;
    font-family: PingFang SC-Bold, PingFang SC;
    font-weight: bold;
    color: #1F6A9D;
    margin-bottom: 15px;
  }

  .camera_tip {
    font-size: 12px;
    color: #666666;
  }


  .update_idcard {
    border-radius: 8px;
    margin-top: 10px;
    padding: 5px 0;

    .update_item {
      margin-bottom: 10px;
      border-radius: 5px;
      text-align: center;
      padding: 5px;
      position: relative;

      .image {
        height: 150px;
        width: 250px;
      }

      .camera {
        height: 50px;
        width: 50px;
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%)
      }

      .text {
        font-size: 14px;
        margin: 10px 0;
        color: #999999;
      }
    }
  }

  .uploadTips {
    margin-top: 30%;
    padding: 0 25px;

    .box {
      width: 100%;
      border-radius: 4px;
      background-color: #fff;
      font-size: 16px;

      .title {
        text-align: center;
        padding: 10px;
        border: 1px solid #f4f4f4;
      }

      .img_tips_center {
        padding: 15px 20px;

      }
    }

    .close {
      margin-top: 20px;
      text-align: center;
    }
  }

  .confirm_form {
    padding: 15px 15px 0 15px;
    height: 50vh;
    overflow: auto;

    .confirm_item {
      margin-bottom: 15px;

      .label {
        margin-bottom: 7px;
        color: #4a4a4a;
      }

      .text {
        border-bottom: 1px solid #E3E3E3;
        line-height: 32px;
      }
    }
  }

  .confirm_tips {
    font-size: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0 15px;
  }

  .confirm_tips img {
    height: 17px;
    width: 14px;
    margin-right: 3px;
  }
}
</style>
